<template>
  <div class="system-management-container app-container">
    <div class="search-box">
      <TabSearch
        label-width="90px"
        :data="searchData"
        @searchForm="searchForm"
        @resetForm="resetForm"
      />
    </div>
    <div class="content-main">
      <div class="content-side">
        <el-tree
          class="filter-tree"
          :data="asideList"
          :props="defaultProps"
          :default-expand-all="expanded"
          :default-checked-keys="checkedKeys"
          :check-strictly="false"
          node-key="id"
          ref="tree"
        ></el-tree>
        <!-- <ul>
          <li v-for="(item, index) in asideList" :key="index">
            <div>
              <i v-show="item.pId === '0'" class="el-icon-document first-icon" />
              <i v-show="index > 0 && index !== 4" class="el-icon-circular" />
              <i v-show="index > 0 && index === 4" class="el-icon-phone-outline active-icon"></i>
              <span :class="{'active-ele': index === 4}">{{ item.name }}</span>
            </div>
            <div class="side-line" v-show="index+1 !== asideList.length" />
          </li>
        </ul>-->
      </div>
      <div class="list-wrapper" style="flex: 1;">
        <div class="content">
          <div class="title">
            <span>用户管理</span>
          </div>
          <div class="operation">
            <el-button type="primary" @click="handleAdd">新增</el-button>
            <!-- <el-button @click="handleEdit">修改</el-button> -->
            <!-- pk_id -->
            <el-button @click="openDelectBox('pk_id')">删除</el-button>
            <el-button @click="openExportBox">导出</el-button>
          </div>
          <comm-table
            ref="dragTable"
            :loading="loading"
            :data="tableData"
            @iPagination="iPagination"
            @selectionChange="selectionChange"
            style="width: 100%"
          >
            <el-table-column width="80" type="selection" />
            <el-table-column prop="login_name" label="登录名称" width="150" />
            <el-table-column prop="user_name" label="用户名称" width="150" />
            <el-table-column prop="dept_name" label="部门" width="150" />
            <el-table-column prop="phonenumber" label="手机" width="150" />
            <el-table-column prop="status" label="状态" width="150">
              <template slot-scope="scope">
                <span v-if="scope.row.status === '0'">正常</span>
                <span v-else-if="scope.row.status === '1'">停用</span>
              </template>
            </el-table-column>
            <el-table-column prop="create_time" label="创建时间" width="250" show-overflow-tooltip />
            <el-table-column label="操作" width="220">
              <template slot-scope="scope">
                <span class="operation-btn" @click="handleEdit(scope)">编辑</span>
                <span class="operation-btn" @click="openDelectBox({ ids: scope.row.pk_id })">删除</span>
                <span class="operation-btn" @click="handleReset(scope)">重置</span>
              </template>
            </el-table-column>
          </comm-table>
        </div>
      </div>
    </div>
    <div v-if="dialogVisible">
      <!-- top="5vh" -->
      <el-dialog
        :title="title + '用户'"
        :visible.sync="dialogVisible"
        width="50%"
        class="handle-dialog"
        :destroy-on-close="true"
        top="5vh"
        @close="dialogVisible = false"
      >
        <!-- @handleCancel="handleCancel"
        @handleConfirm="handleConfirm"-->
        <add-user ref="addDialog" :titles="title" />
        <span slot="footer" class="dialog-footer">
          <el-button type="primary" @click="handleConfirm">确定</el-button>
          <el-button @click="dialogVisible = false">关闭</el-button>
        </span>
      </el-dialog>
    </div>
    <div v-if="resetDialogVisible">
      <el-dialog
        title="重置密码"
        :visible.sync="resetDialogVisible"
        width="50%"
        class="handle-dialog"
        :destroy-on-close="true"
        @close="resetDialogVisible = false"
      >
        <reset-user ref="resetDialog" :title="title" />
        <span slot="footer" class="dialog-footer">
          <el-button type="primary" @click="resetPasswordConfirm">确定</el-button>
          <el-button @click="resetDialogVisible = false">关闭</el-button>
        </span>
      </el-dialog>
    </div>
  </div>
</template>

<script>
import TabSearch from "@/components/TabSearch";
import AddUser from "../modules/addUser";
import ResetUser from "../modules/resetUser";
import TableCommMixin from "@/mixins/TableCommMixin";
import SystemMixin from "@/mixins/SystemMixin";
import {
  getGetDeptTreeData, // 部门树
  getRoleDeptTreeData, // 由角色id获取部门树
  getUserDeptInfo,
  getUserDetail, // 详情
  getUserRoleList, // 角色
  getUserPostList, // 部门
  checkPassword, // 密码检测
  // checkLoginNameUnique, // 检查用户登录名称唯一性
  // checkPhoneUnique, // 检查用户用户手机号唯一性
  // checkEmailUnique, // 检查用户邮箱唯一性
  resetPwdSet // 重置密码
} from "@/api/api";
export default {
  name: "UserManagement",
  components: {
    TabSearch,
    AddUser,
    ResetUser
  },
  mixins: [TableCommMixin, SystemMixin],
  data() {
    return {
      title: "",
      dialogVisible: false,
      resetDialogVisible: false,
      queryConditions: {},
      url: {
        // 列表数据
        list: "/system/api/User",
        method: "get",
        // 新增 {roleIds}/{postIds}
        add: "/system/api/User",
        // add: '/system/api/User',
        addMethod: "post",
        // 编辑
        // edit: '/system/api/User/1/5cb23e18-42fc-4077-a49e-590cb80c38c1',
        edit: "/system/api/User",
        editMethod: "put",
        // 删除
        delete: "/system/api/User",
        deleteMethod: "delete",
        // 导出
        export: "/system/api/User/Export"
      },
      searchData: [
        {
          key: "login_name",
          title: "登录名称 ",
          type: "input",
          attr: {
            placeholder: "请输入"
          }
        },
        {
          key: "create_date",
          title: "创建时间",
          type: "time",
          attr: {
            placeholder: "请选择"
          }
        },
        // {
        //   key: 'status',
        //   title: '用户状态',
        //   type: 'arrow',
        //   attr: {
        //     placeholder: '所有'
        //   }
        // },
        {
          key: "status",
          title: "用户状态",
          type: "select",
          attr: {
            placeholder: "所有"
          },
          options: [
            {
              // value: 0,
              label: "所有"
            },
            {
              value: 0,
              label: "正常"
            },
            {
              value: 1,
              label: "停用"
            }
          ]
        },
        {
          key: "phonenumber",
          title: "手机号码",
          type: "input",
          attr: {
            placeholder: "请输入"
          }
        }
      ],
      // userTableData: [],
      asideList: [],
      defaultProps: {
        children: "children",
        label: "name"
      },
      expanded: true,
      checkedKeys: []
    };
  },
  mounted() {
    // 部门树
    getGetDeptTreeData().then(res => {
      if (res.code === 0) {
        this.asideList = this.assembleTreeData(res.data, "id", "pId");
      }
    });
    // 获取用户的部门 this.uid
    getUserDeptInfo({ pid: this.uid }).then(res => {
      if(res.code === 0) {
        this.checkedKeys[0] = res.data['dept_id'] ? res.data['dept_id'] : ''
        console.log(res.data, "getUserDeptInfo");
      }
    });
  },
  methods: {
    // 删除
    openDelectBox(param) {
      this.$confirm("此操作将此用户删除吗, 是否继续?", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning"
      })
        .then(() => {
          if (typeof param === "string") {
            this.handleDelete(param);
          } else {
            this.handleDeleteOne(param);
          }
        })
        .catch(() => {
          this.$message({
            type: "warning",
            message: "已取消删除"
          });
        });
    },
    // 导出
    openExportBox() {
      this.$confirm("确定导出数据至EXCEL吗?", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning"
      })
        .then(() => {
          this.handleExport();
        })
        .catch(() => {
          this.$message({
            type: "warning",
            message: "已取消导出"
          });
        });
    },
    // 编辑之前
    async beforeEdit(data) {
      let roleIds = [];
      let postIds = [];
      await getUserRoleList({ pid: data.row.pk_id }).then(res => {
        if (res.code === 0) {
          if (res.data && res.data.length) {
            roleIds = res.data.filter(ite => ite.checkd === data.row.pk_id);
          }
        }
      });
      await getUserPostList({ pid: data.row.pk_id }).then(res => {
        if (res.code === 0) {
          if (res.data && res.data.length) {
            postIds = res.data.filter(ite => ite.selectd === data.row.pk_id);
          }
        }
      });
      return new Promise((resolve, reject) => {
        getUserDetail({ pid: data.row.pk_id }).then(res => {
          if (res.code === 0) {
            console.log(res.data, "beforeEdit");
            // 唯一性检测
            if (!res.data["checkParam"]) {
              res["data"]["checkParam"] = {
                uniqueNameValue: false,
                // uniquePasswordValue: false,
                uniqueEmailValue: false,
                uniquePhoneValue: false
              };
            }
            if (roleIds.length) {
              res.data["roleIds"] = roleIds.map(item => item.pk_id);
            }
            if (postIds.length) {
              res.data["postIds"] = postIds.map(item => item.pk_id);
            }
            resolve(res.data);
          } else {
            this.$message({ type: "error", message: res.msg });
            reject({});
          }
        });
      });
    },
    // 提交之前
    async beforeSubmit(data) {
      // let checkPw = true
      // if(data['pk_id']) {
      //    checkPw = await this.handleCheckPassword(data['pk_id'], data['password'])
      // }
      return new Promise(resolve => {
        let adoptValue = false;
        // 岗位
        if (data["postIds"] instanceof Array && data["postIds"].length) {
          data["postIds"] = data["postIds"].join(",");
        }
        // 角色
        if (data["roleIds"] instanceof Array && data["roleIds"].length) {
          data["roleIds"] = data["roleIds"].join(",");
        }
        // if (this.loginName) {
        //   data['login_name'] = this.loginName
        //   // this.loginName = JSON.parse(localStorage.getItem('userInfo'))['profile']['LoginName']
        // }
        // if (this.action == "add") {
        //   this.url.add = `/system/api/User/${data['postIds']}/${data['postIds']}`
        // } else if(this.action == "edit") {
        //   this.url.edit = `/system/api/User/${data['roleIds']}/${data['postIds']}`
        // }
        // 唯一性检测
        if (data["checkParam"]) {
          if (Object.values(data["checkParam"]).length) {
            Object.values(data["checkParam"]).some(item => {
              if (item) {
                adoptValue = true;
              }
            });
          }
        }
        if (this.action == "add") {
          this.url.add =
            "/system/api/User" + "/" + data["roleIds"] + "/" + data["postIds"];
          // this.url.add = `/system/api/User/${data['postIds']}/${data['postIds']}`
        } else if (this.action == "edit") {
          this.url.edit = `/system/api/User/${data["roleIds"]}/${data["postIds"]}`;
        }
        if (adoptValue) {
          resolve({ status: -1 });
        } else {
          resolve(data);
        }
      });
    },
    // 重置密码
    handleReset(data) {
      getUserDetail({ pid: data.row.pk_id }).then(res => {
        if (res.code === 0) {
          this.resetDialogVisible = true;
          this.$nextTick(() => {
            this.$refs["resetDialog"]["form"] = JSON.parse(
              JSON.stringify(res.data)
            );
            console.log(res.data, "handleReset");
            // setTimeout(() => {
            //   this.$refs['resetDialog']['form'] = JSON.parse(JSON.stringify(res.data))
            // }, 200)
          });
        }
      });
    },
    // 重置密码确认
    async resetPasswordConfirm() {
      let param = this.$refs["resetDialog"]["form"];
      console.log(param, "resetPasswordConfirm");
      if (this.$refs["resetDialog"]["rules"]) {
        let validStatus = await this.$refs["resetDialog"]["$refs"]["form"]
          .validate()
          .then(valid => {
            return new Promise(resolve => {
              resolve(valid);
            });
          });
        if (!validStatus) return false;
      }
      // 密码验证有问题 --------------------------------
      let checkPw = await this.handleCheckPassword(
        param["pk_id"],
        param["oldPassword"]
      );
      if (!checkPw) {
        return this.$message.error("原密码错误");
      }
      if (param["newPassword"] && param["confirmPassword"]) {
        if (param["newPassword"] !== param["confirmPassword"]) {
          return this.$message.error("两次密码输入不一致");
        } else {
          resetPwdSet({
            pk_id: param["pk_id"] ? param["pk_id"] : "",
            password: param["newPassword"] ? param["newPassword"] : ""
          }).then(res => {
            if (res.code === 0) {
              this.$message.success(res.msg);
            } else {
              this.$message.error("密码修改失败");
            }
            this.resetDialogVisible = false;
          });
        }
      }
    },
    // 检测密码
    handleCheckPassword(id, pw) {
      checkPassword({
        userId: id ? id : "",
        password: pw ? pw : ""
      }).then(res => {
        if (res.code === 0 || res.code === 500) return res["data"];
      });
    }
  }
};
</script>

<style lang="scss" scoped>
.system-management-container {
  margin: 0 22px;
  .search-box {
    margin-top: 20px;
    background: rgba(245, 247, 249, 1);
    border: 1px solid rgba(221, 221, 221, 1);
    padding-top: 13px;
  }
  .content-main {
    display: flex;
    background: #fff;
    .content-side {
      background: rgba(255, 255, 255, 1);
      border: 1px solid rgba(221, 221, 221, 1);
      margin-right: 23px;
      padding: 20px 50px 0px 36px;
      ul {
        padding: 30px 100px 0px 36px;
        li {
          // display: flex;
          white-space: nowrap;
          width: 100%;
          .side-line {
            width: 1px;
            height: 25px;
            // height: 55px;
            background: rgb(229, 229, 233);
            margin: 12px;
          }
          span {
            // white-space: nowrap;
          }
          .first-icon {
            font-size: 25px;
            color: rgba(241, 131, 0, 1);
          }
          .el-icon-circular {
            display: inline-block;
            width: 10px;
            height: 10px;
            border: 2px solid rgba(126, 145, 188, 1);
            border-radius: 50%;
            box-sizing: border-box;
            margin-left: 7px;
          }
          .active-icon {
            font-size: 20px;
            color: #394662;
          }
          .active-ele {
            font-size: 18px;
            font-weight: bold;
            color: rgba(57, 70, 98, 1);
          }
        }
      }
    }
  }
}
</style>
